package com.lilingguo.easyserver.container;

import com.lilingguo.easyserver.pojo.ServiceInfo;

import java.util.*;
import java.util.concurrent.ConcurrentMap;

/**
 * 默认容器
 * 使用 ConcurrentHashMap
 *
 * @Author: 黎铃果
 * @Date: 2020/05/28 16:34
 */
public class DefaultContainer implements Container {

    private final ConcurrentMap<String, ServiceInfo> serviceData;

    public DefaultContainer(ConcurrentMap<String, ServiceInfo> serviceData) {
        this.serviceData = serviceData;
    }

    @Override
    public void init() {

    }

    @Override
    public boolean saveInfo(ServiceInfo info) {
        info.setTtl(System.currentTimeMillis());
        String idStr = info.getIdStr();
        Set<String> set = serviceData.keySet();
        if (set.contains(idStr)) {
            return false;
        }
        serviceData.put(idStr, info);
        return true;
    }

    @Override
    public boolean removeInfo(ServiceInfo info) {
        return serviceData.remove(info.getIdStr(), info);
    }

    @Override
    public void removeExpiredInfos() {
        long time = System.currentTimeMillis();
        Collection<ServiceInfo> values = serviceData.values();
        values.removeIf(info -> info.getTtl() + info.getMaximalLife() < time);
    }

    @Override
    public Set<ServiceInfo> getInfo(String serverName) {
        HashSet<ServiceInfo> set = new HashSet<>();
        for (ServiceInfo info : serviceData.values()) {
            if (info.getName().equals(serverName)) {
                set.add(info);
            }
        }
        return set;
    }

    @Override
    public Set<ServiceInfo> getAllData() {
        return new HashSet<>(serviceData.values());
    }

    @Override
    public boolean keepAlive(ServiceInfo info) {
        info.setTtl(System.currentTimeMillis());
        String idStr = info.getIdStr();
        if (serviceData.containsKey(idStr)) {
            serviceData.put(idStr, info);
            return true;
        }
        return false;
    }

}
